cmake_minimum_required(VERSION 3.15)

# xxxxxxxxxxxxxxxxxxx vcpkg配置，必须位于project之前
include(cmake/mypath.cmake)
include(cmake/myvcpkg.cmake)

# xxxxxxxxxxxxxxxxxxx project root
project(pycppcomp LANGUAGES CXX)

# ----- fmt lib
find_package(fmt CONFIG REQUIRED)

# ----- pybind11
find_package(Python COMPONENTS Interpreter Development) # advanced mode
find_package(pybind11 CONFIG REQUIRED)

# ----- python3
find_package(Python3 REQUIRED COMPONENTS Interpreter Development)
message(STATUS "Python3 found at: ${Python3_EXECUTABLE}")

# ----- hdf5 serialize
find_package(HDF5 REQUIRED)

# ----- google Test
find_package(GTest REQUIRED)

set(mylib math_lib)
set(mytest math_lib_test)
set(mypy11 math_lib_cpp)

# =================== C++ 数学库
add_library(${mylib} STATIC cpp/math_lib.cpp cpp/math_lib.h)
target_include_directories(${mylib} PUBLIC cpp)

# =================== C++ 单元测试
add_executable(${mytest}
    cpp/tests/math_lib_test.cpp
    cpp/tests/PrePythonData.h
)

get_filename_component(MYPY3_HOME ${Python3_EXECUTABLE} DIRECTORY)
target_compile_definitions(${mytest} PRIVATE
    MYPROGRAME_NAME="${mytest}"
    MY_SOURCE_ROOT="${ROOT_DIR}"
    MY_BINARY_ROOT="${PATH_BIN}"
    MYPYTHON3_HOME="${MYPY3_HOME}"
)
target_link_libraries(${mytest}
    PRIVATE
    math_lib
    fmt::fmt-header-only
    GTest::GTest GTest::Main
    Python3::Python
    hdf5::hdf5-shared
)

# ------------ 拷贝依赖的 DLL 到构建目录
add_custom_command(TARGET ${mytest} POST_BUILD
    COMMAND ${CMAKE_COMMAND} -E copy_if_different $<TARGET_RUNTIME_DLLS:${mytest}> $<TARGET_FILE_DIR:${mytest}>
    COMMAND_EXPAND_LISTS
    COMMENT "Copying DLLs to build directory")

# =================== pybind11 绑定; cpp -> python .pyd
Python_add_library(${mypy11} cpp/bindings.cpp)
target_link_libraries(${mypy11}
    PRIVATE math_lib pybind11::pybind11_headers)

# ------------------- 拷贝 .pyd 文件到测试目录
add_custom_command(TARGET ${mypy11} POST_BUILD
    COMMAND ${CMAKE_COMMAND} -E copy_if_different $<TARGET_FILE:${mypy11}> "${ROOT_DIR}/python/tests")

# =================== Visual Studio 设置
set_property(DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR} PROPERTY VS_STARTUP_PROJECT ${mytest})

# =================== 安装目标
install(TARGETS
    ${mypy11} DESTINATION python
)